import {defineStore} from 'pinia'
import {router} from '@/router'
import {chatMessageApi} from '@/api/chat/chatMessage.api'

export function defaultState(): Chat.ChatState {
    const uuid = 1002
    return {
        active: uuid,
        usingContext: true,
        history: [{uuid, title: 'New Chat', isEdit: false , id:uuid}],
        chat: [{uuid, data: []}],
    }
}

export const useChatStore = defineStore('chat-store', {
    state: (): Chat.ChatState => defaultState(),
    getters: {
        getChatHistoryByCurrentActive(state: Chat.ChatState) {
            const index = state.history.findIndex(item => item.uuid === state.active)
            if (index !== -1)
                return state.history[index]
            return null
        },
        getChatByUuid(state: Chat.ChatState) {
            return (uuid?: number) => {
                if (uuid){
                    console.log("uuid: ", state.chat.find(item => item.uuid === uuid)?.data ?? [])
                    return state.chat.find(item => item.uuid === uuid)?.data ?? []
                } else {
                    return state.chat.find(item => item.uuid === state.active)?.data ?? []
                }
            }
        }
    },
    actions: {
        async fetchChatHistory() {
            // this.isLoading = true
            const response = await chatMessageApi.getChatState();
            this.$state = response.data;
            console.log(this.$state);
        },

        setUsingContext(context: boolean) {
            this.usingContext = context
            this.recordState()
        },
        getChatRoom(){
            return this.$state.history;
        },
        addHistory(history: Chat.History, chatData: Chat.Chat[] = []) {
            this.history.unshift(history)
            this.chat.unshift({uuid: history.uuid, data: chatData})
            this.active = history.uuid
            this.reloadRoute(history.uuid)
        },
        getActiveUuid() {
            return this.active;
        },
        updateHistory(uuid: number, edit: Partial<Chat.History>) {
            const index = this.history.findIndex(item => item.uuid === uuid)
            if (index !== -1) {
                this.history[index] = {...this.history[index], ...edit}
                this.recordState()
            }
        },

        async deleteHistory(index: number) {
            this.history.splice(index, 1)
            this.chat.splice(index, 1)

            if (this.history.length === 0) {
                this.active = null
                this.reloadRoute()
                return
            }

            if (index > 0 && index <= this.history.length) {
                const uuid = this.history[index - 1].uuid
                this.active = uuid
                this.reloadRoute(uuid)
                return
            }

            if (index === 0) {
                if (this.history.length > 0) {
                    const uuid = this.history[0].uuid
                    this.active = uuid
                    this.reloadRoute(uuid)
                }
            }

            if (index > this.history.length) {
                const uuid = this.history[this.history.length - 1].uuid
                this.active = uuid
                this.reloadRoute(uuid)
            }
        },

        async setActive(uuid: number) {
            this.active = uuid
        },

        getChatByUuidAndIndex(uuid: number, index: number) {
            if (!uuid || uuid === 0) {
                if (this.chat.length)
                    return this.chat[0].data[index]
                return null
            }
            const chatIndex = this.chat.findIndex(item => item.uuid === uuid)
            if (chatIndex !== -1)
                return this.chat[chatIndex].data[index]
            return null
        },

        addChatByUuid(uuid: number, chat: Chat.Chat) {
            if (!uuid || uuid === 0) {
                if (this.history.length === 0) {
                    const uuid = Date.now()
                    this.history.push({uuid, title: chat.text, isEdit: false,id: uuid})
                    this.chat.push({uuid, data: [chat]})
                    this.active = uuid
                    this.recordState()
                } else {
                    this.chat[0].data.push(chat)
                    if (this.history[0].title === 'New Chat')
                        this.history[0].title = chat.text
                    this.recordState()
                }
            }

            const index = this.chat.findIndex(item => item.uuid === uuid)
            if (index !== -1) {
                this.chat[index].data.push(chat)
                if (this.history[index].title === 'New Chat')
                    this.history[index].title = chat.text
                this.recordState()
            }
        },

        updateChatByUuid(uuid: number, index: number, chat: Chat.Chat) {
            if (!uuid || uuid === 0) {
                if (this.chat.length) {
                    this.chat[0].data[index] = chat
                    this.recordState()
                }
                return
            }

            const chatIndex = this.chat.findIndex(item => item.uuid === uuid)
            if (chatIndex !== -1) {
                this.chat[chatIndex].data[index] = chat
                this.recordState()
            }
        },

        updateChatSomeByUuid(uuid: number, index: number, chat: Partial<Chat.Chat>) {
            if (!uuid || uuid === 0) {
                if (this.chat.length) {
                    this.chat[0].data[index] = {...this.chat[0].data[index], ...chat}
                    this.recordState()
                }
                return
            }

            const chatIndex = this.chat.findIndex(item => item.uuid === uuid)
            if (chatIndex !== -1) {
                this.chat[chatIndex].data[index] = {...this.chat[chatIndex].data[index], ...chat}
                this.recordState()
            }
        },

        deleteChatByUuid(uuid: number, index: number) {
            if (!uuid || uuid === 0) {
                if (this.chat.length) {
                    this.chat[0].data.splice(index, 1)
                    this.recordState()
                }
                return
            }

            const chatIndex = this.chat.findIndex(item => item.uuid === uuid)
            if (chatIndex !== -1) {
                this.chat[chatIndex].data.splice(index, 1)
                this.recordState()
            }
        },

        clearChatByUuid(uuid: number) {
            if (!uuid || uuid === 0) {
                if (this.chat.length) {
                    this.chat[0].data = []
                    this.recordState()
                }
                return
            }

            const index = this.chat.findIndex(item => item.uuid === uuid)
            if (index !== -1) {
                this.chat[index].data = []
                this.recordState()
            }
        },
        async onInit() {
            await this.fetchChatHistory()
        },
        async reloadRoute(uuid?: number) {
            this.recordState()
            await router.push({name: 'Chat', params: {uuid}})
        },

        recordState() {
            // setLocalState(this.$state)
        },
    },
})
